<template>
    <div class="chat-container">
        <!-- 联系人列表 -->
        <div class="contacts-panel">
            <div class="contacts-header">
                <h3>消息</h3>
            </div>
            <div class="contacts-list">
                <div v-for="contact in contacts" :key="contact.id" :class="['contact-item', { active: activeContactId === contact.id }]" @click="selectContact(contact)">
                    <div class="contact-avatar">
                        <img :src="contact.avatar" :alt="contact.name" />
                        <span v-if="contact.isOnline" class="online-status"></span>
                    </div>
                    <div class="contact-info">
                        <div class="contact-name">{{ contact.name }}</div>
                        <div class="contact-last-message">{{ contact.lastMessage }}</div>
                    </div>
                    <div class="contact-meta">
                        <div class="contact-time">{{ formatTime(contact.lastMessageTime) }}</div>
                        <div v-if="contact.unreadCount > 0" class="unread-badge">
                            {{ contact.unreadCount }}
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="chat-panel">
            <div v-if="activeContact" class="chat-header">
                <div class="chat-header-info">
                    <img :src="activeContact.avatar" :alt="activeContact.name" />
                    <div>
                        <div class="chat-contact-name">{{ activeContact.name }}</div>
                        <div class="chat-contact-status">
                            {{ activeContact.isOnline ? '在线' : '离线' }}
                        </div>
                    </div>
                </div>
            </div>

            <div v-else class="chat-header-placeholder">
                <p>选择一个联系人开始聊天</p>
            </div>

            <div ref="messageContainer" class="chat-messages" v-if="activeContact">
                <div v-for="message in filteredMessages" :key="message.id" :class="['message', message.sender === currentUser.id ? 'sent' : 'received']">
                    <div class="message-content">
                        <div class="message-text">{{ message.content }}</div>
                        <div class="message-info">
                            <span class="message-time">{{ formatTime(message.timestamp) }}</span>
                            <span v-if="message.sender === currentUser.id" class="message-status">
                                <i v-if="message.status === 'sent'" class="status-icon sent">✓</i>
                                <i v-else-if="message.status === 'delivered'" class="status-icon delivered">✓✓</i>
                                <i v-else-if="message.status === 'read'" class="status-icon read">✓✓</i>
                            </span>
                        </div>
                    </div>
                </div>
            </div>

            <div v-if="activeContact" class="chat-input">
                <input v-model="newMessage" @keyup.enter="sendMessage" placeholder="输入消息..." type="text" />
                <button @click="sendMessage" :disabled="!newMessage.trim()">发送</button>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    name: 'Test',
    data() {
        return {
            currentUser: {
                id: 'currentUser',
                name: '我',
                avatar: 'https://ts1.tc.mm.bing.net/th/id/OIP-C.UyaBji0AU_6M3VDA2F1RvgAAAA?rs=1&pid=ImgDetMain&o=7&rm=3',
            },
            activeContactId: null,
            newMessage: '',
            contacts: [
                {
                    id: 'user1',
                    name: '张三',
                    avatar: 'https://www.keaitupian.cn/cjpic/frombd/1/253/3663778712/1545220977.jpg',
                    lastMessage: '好的，我可以为您详细介绍',
                    lastMessageTime: '2023-10-01 10:30:00',
                    unreadCount: 1,
                    isOnline: true,
                },
                {
                    id: 'user2',
                    name: '李四',
                    avatar: 'https://www.keaitupian.cn/cjpic/frombd/0/253/2279408239/3825398873.jpg',
                    lastMessage: '明天见',
                    lastMessageTime: '2023-09-30 15:45:00',
                    unreadCount: 0,
                    isOnline: false,
                },  
            ],
            messages: [
                {
                    id: 1,
                    content: '你好，有什么可以帮助你的吗？',
                    sender: 'user1',
                    receiver: 'currentUser',
                    timestamp: '2023-10-01 10:30:00',
                    status: 'read',
                },
                {
                    id: 2,
                    content: '我想了解一下产品信息',
                    sender: 'currentUser',
                    receiver: 'user1',
                    timestamp: '2023-10-01 10:32:00',
                    status: 'read',
                },
                {
                    id: 3,
                    content: '好的，我可以为您详细介绍',
                    sender: 'user1',
                    receiver: 'currentUser',
                    timestamp: '2023-10-01 10:35:00',
                    status: 'read',
                },
            ],
        }
    },
    computed: {
        activeContact() {
            return this.contacts.find(
                (contact) => contact.id === this.activeContactId
            )
        },
        filteredMessages() {
            if (!this.activeContactId) return []
            return this.messages.filter(
                (msg) =>
                    (msg.sender === this.activeContactId &&
                        msg.receiver === this.currentUser.id) ||
                    (msg.sender === this.currentUser.id &&
                        msg.receiver === this.activeContactId)
            )
        },
    },
    watch: {
        activeContactId(newId) {
            if (newId) {
                // 标记消息为已读
                this.markMessagesAsRead(newId)
                this.$nextTick(() => {
                    this.scrollToBottom()
                })
            }
        },
        filteredMessages() {
            this.$nextTick(() => {
                this.scrollToBottom()
            })
        },
    },
    methods: {
        selectContact(contact) {
            this.activeContactId = contact.id
        },
        sendMessage() {
            if (!this.newMessage.trim()) return

            const message = {
                id: Date.now(),
                content: this.newMessage,
                sender: this.currentUser.id,
                receiver: this.activeContactId,
                timestamp: new Date()
                    .toLocaleString('zh-CN', {
                        year: 'numeric',
                        month: '2-digit',
                        day: '2-digit',
                        hour: '2-digit',
                        minute: '2-digit',
                        hour12: false,
                    })
                    .replace(/\//g, '-'),
                status: 'sent',
            }

            this.messages.push(message)

            // 更新联系人最后消息
            const contact = this.contacts.find(
                (c) => c.id === this.activeContactId
            )
            if (contact) {
                contact.lastMessage = this.newMessage
                contact.lastMessageTime = message.timestamp
            }

            this.newMessage = ''

            // 模拟消息状态更新
            setTimeout(() => {
                message.status = 'delivered'
            }, 1000)
        },
        markMessagesAsRead(contactId) {
            // 将来自该联系人的未读消息标记为已读
            this.messages.forEach((msg) => {
                if (
                    msg.sender === contactId &&
                    msg.receiver === this.currentUser.id &&
                    msg.status !== 'read'
                ) {
                    msg.status = 'read'
                }
            })

            // 清除未读计数
            const contact = this.contacts.find((c) => c.id === contactId)
            if (contact) {
                contact.unreadCount = 0
            }
        },
        formatTime(timestamp) {
            const date = new Date(timestamp)
            const now = new Date()

            // 如果是今天，只显示时间
            if (date.toDateString() === now.toDateString()) {
                return date.toLocaleTimeString('zh-CN', {
                    hour: '2-digit',
                    minute: '2-digit',
                    hour12: false,
                })
            }

            // 如果是今年，显示月日和时间
            if (date.getFullYear() === now.getFullYear()) {
                return (
                    date.toLocaleDateString('zh-CN', {
                        month: '2-digit',
                        day: '2-digit',
                    }) +
                    ' ' +
                    date.toLocaleTimeString('zh-CN', {
                        hour: '2-digit',
                        minute: '2-digit',
                        hour12: false,
                    })
                )
            }

            // 其他情况显示完整日期
            return date.toLocaleDateString('zh-CN')
        },
        scrollToBottom() {
            const container = this.$refs.messageContainer
            if (container) {
                container.scrollTop = container.scrollHeight
            }
        },
    },
    mounted() {
        // 初始化时滚动到底部
        this.$nextTick(() => {
            this.scrollToBottom()
        })
    },
}
</script>

<style scoped>
.chat-container {
    display: flex;
    height: 80vh;
    background-color: #f5f5f5;
}

.contacts-panel {
    width: 300px;
    background: white;
    border-right: 1px solid #e0e0e0;
    display: flex;
    flex-direction: column;
}

.contacts-header {
    padding: 20px;
    border-bottom: 1px solid #e0e0e0;
}

.contacts-header h3 {
    margin: 0;
    font-size: 18px;
}

.contacts-list {
    flex: 1;
    overflow-y: auto;
}

.contact-item {
    display: flex;
    padding: 15px;
    border-bottom: 1px solid #f0f0f0;
    cursor: pointer;
    transition: background-color 0.2s;
}

.contact-item:hover {
    background-color: #f9f9f9;
}

.contact-item.active {
    background-color: #e3f2fd;
}

.contact-avatar {
    position: relative;
    margin-right: 12px;
}

.contact-avatar img {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    object-fit: cover;
}

.online-status {
    position: absolute;
    bottom: 0;
    right: 0;
    width: 12px;
    height: 12px;
    background-color: #4caf50;
    border: 2px solid white;
    border-radius: 50%;
}

.contact-info {
    flex: 1;
    overflow: hidden;
}

.contact-name {
    font-weight: 500;
    margin-bottom: 4px;
}

.contact-last-message {
    font-size: 14px;
    color: #666;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.contact-meta {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    justify-content: space-between;
}

.contact-time {
    font-size: 12px;
    color: #999;
}

.unread-badge {
    background-color: #ff4757;
    color: white;
    border-radius: 10px;
    padding: 2px 6px;
    font-size: 12px;
    margin-top: 4px;
}

.chat-panel {
    flex: 1;
    display: flex;
    flex-direction: column;
}

.chat-header {
    padding: 15px 20px;
    background: white;
    border-bottom: 1px solid #e0e0e0;
    display: flex;
    align-items: center;
}

.chat-header-info {
    display: flex;
    align-items: center;
}

.chat-header-info img {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 12px;
}

.chat-contact-name {
    font-weight: 500;
}

.chat-contact-status {
    font-size: 12px;
    color: #666;
}

.chat-header-placeholder {
    padding: 20px;
    text-align: center;
    color: #999;
    background: white;
    border-bottom: 1px solid #e0e0e0;
}

.chat-messages {
    flex: 1;
    padding: 20px;
    overflow-y: auto;
    background: #f0f8ff;
}

.message {
    display: flex;
    margin-bottom: 15px;
}

.message.received {
    justify-content: flex-start;
}

.message.sent {
    justify-content: flex-end;
}

.message-content {
    max-width: 70%;
}

.message.received .message-content {
    background: white;
    border-radius: 18px 18px 18px 4px;
    padding: 12px 16px;
}

.message.sent .message-content {
    background: #2196f3;
    color: white;
    border-radius: 18px 4px 18px 18px;
    padding: 12px 16px;
}

.message-text {
    word-wrap: break-word;
    margin-bottom: 4px;
}

.message-info {
    display: flex;
    justify-content: flex-end;
    font-size: 12px;
}

.message.received .message-info {
    color: #999;
}

.message.sent .message-info {
    color: rgba(255, 255, 255, 0.8);
}

.status-icon {
    margin-left: 4px;
}

.status-icon.sent {
    color: #999;
}

.status-icon.delivered {
    color: #999;
}

.status-icon.read {
    color: #b92727;
}

.chat-input {
    padding: 15px;
    background: white;
    border-top: 1px solid #e0e0e0;
    display: flex;
}

.chat-input input {
    flex: 1;
    padding: 12px;
    border: 1px solid #e0e0e0;
    border-radius: 20px;
    outline: none;
}

.chat-input button {
    margin-left: 10px;
    padding: 12px 20px;
    background: #2196f3;
    color: white;
    border: none;
    border-radius: 20px;
    cursor: pointer;
}

.chat-input button:disabled {
    background: #bbdefb;
    cursor: not-allowed;
}
</style>